package com.zhangfuxing.datatools.core;

import com.zhangfuxing.datatools.Starter;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 张福兴
 * @version 1.0
 * @date 2024/10/2
 * @email zhangfuxing1010@163.com
 */
public class AppContext {
    public static AppContext context;
    Map<Class<?>, Map<String, Object>> instances = new HashMap<>();
    Class<?> starterClass;
    String[] args;

    public AppContext() {
    }

    public static void starter(Class<Starter> starterClass, String[] args) {
        AppContext.context = new AppContext();
        context.starterClass = starterClass;
        context.args = args;
        register(AppConfig.class, "appConfig", new AppConfig());
        register(CommandReader.class, "commandReader", new CommandReader());
        EntryPoint entryPoint = new EntryPoint();
        entryPoint.run();
    }

    public static void register(final Class<?> clazz, final String name, final Object instance) {
        Map<String, Object> map = context.instances.get(clazz);
        if (map == null) {
            map = new HashMap<>();
        }
        map.put(name, instance);
        context.instances.put(clazz, map);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(final Class<T> clazz) {
        Map<String, Object> map = context.instances.get(clazz);
        if (map == null) {
            return null;
        }
        T result = null;

        if (map.containsKey(clazz.getName())) {
            result = (T) map.get(clazz.getName());
        } else {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                result = (T) entry.getValue();
                break;
            }
        }

        return result;
    }
}
